import React, { Fragment, useState, useEffect, useReducer } from 'react';
import { Card, notification, Modal, Button } from 'antd';
import { SIZE, PAGE, ALL } from '@/utils/constant';
import { usersList, delUsers, rolesList, batchDelUsers } from '@/services/api';
import UserForm from './components/UserForm';
import EditRoleModal from './components/EditRoleModal';
import EditUserModal from './components/EditUserModal';
import TableList from './components/TableList';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
  },
  searchValue: {},
};

const enumRoles = {
  teacher: '老师',
  parent: '家长',
  student: '学生',
  guard: '门卫',
};

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

function ApplyList() {
  const [roleModal, setRoleModal] = useState(false);
  const [editModal, setEditModal] = useState(false);
  const [delIds, setDelIds] = useState([]);
  const [roleData, setRoleData] = useState([]);
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    rolesList({ page: PAGE, size: ALL }).then((resp: any) => {
      if (resp.status === 'success') {
        setRoleData(resp.data.data);
      }
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    usersList({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const rowSelection = {
    onChange: (selectedRowKeys: any) => {
      setDelIds(selectedRowKeys);
    },
  };

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    usersList({
      ...searchValue,
      page: changePagination.current,
      size: changePagination.pageSize,
    })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '名字',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '性别',
      key: 'sex',
      dataIndex: 'sex',
      render: (text: any) => {
        if (text === 1) {
          return <span>男</span>;
        }
        if (text === 2) {
          return <span>女</span>;
        }
        if (text === 3) {
          return <span>保密</span>;
        }
        return null;
      },
    },
    {
      title: '电话',
      key: 'phone',
      dataIndex: 'phone',
    },
    // {
    //   title: '邮箱',
    //   key: 'email',
    //   dataIndex: 'email',
    // },
    {
      title: '角色',
      key: 'roles',
      dataIndex: 'roles',
      // eslint-disable-next-line arrow-body-style
      render: (text: any) => {
        return text && text.map((item: any) => <div key={item.name}>{enumRoles[item.name]}</div>);
      },
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, object: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <a
            onClick={e => {
              e.preventDefault();
              setEditModal(true);
              sessionStorage.setItem('usersData', JSON.stringify(object));
            }}
          >
            编辑
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              setRoleModal(true);
              sessionStorage.setItem('usersData', JSON.stringify(object));
            }}
          >
            设置角色
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  delUsers(text).then((resp: any) => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      usersList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            删除
          </a>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <Card title="报名列表">
        <UserForm dispatch={dispatch} roleData={roleData} />
      </Card>
      <Card className="pageCard">
        <Button
          type="primary"
          icon="delete"
          onClick={() => {
            if (!delIds.length) {
              notification.error({
                message: '请选择删除用户',
              });
            } else {
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  batchDelUsers({ ids: delIds }).then(resp => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      usersList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }
          }}
        >
          批量删除
        </Button>
        <TableList
          rowSelection={rowSelection}
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
      {roleModal && (
        <EditRoleModal
          dispatch={dispatch}
          onClose={() => {
            setRoleModal(false);
          }}
          roleData={roleData}
          searchValue={searchValue}
        />
      )}
      {editModal && (
        <EditUserModal
          dispatch={dispatch}
          onClose={() => {
            setEditModal(false);
          }}
          roleData={roleData}
          searchValue={searchValue}
        />
      )}
    </Fragment>
  );
}

export default ApplyList;
